<script setup>
import { ref, computed, onMounted } from 'vue'
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { getDishRankingAPI, getMerchantRankingAPI, getHeatRankingAPI } from '@/api/ranking'

const activeTab = ref(0)
const loading = ref(false)

// 为每个标签单独管理hasMore状态
const hasMore = ref({
  dish: true,
  shop: true,
  heat: true
})

// 排行数据
const dishRankingData = ref([])
const shopRankingData = ref([])
const heatRankingData = ref([])

// 当前页码
const currentPage = ref({
  dish: 1,
  shop: 1,
  heat: 1
})

// 标签配置
const tabs = [
  { 
    name: '菜品排行',
    icon: 'dish',
    key: 'dish'
  },
  { 
    name: '店铺排行',
    icon: 'shop',
    key: 'shop'
  },
  { 
    name: '热量排行',
    icon: 'fire',
    key: 'heat'
  }
]

// 当前显示的排行数据
const currentRankingData = computed(() => {
  switch (tabs[activeTab.value].key) {
    case 'dish':
      return dishRankingData.value
    case 'shop':
      return shopRankingData.value
    case 'heat':
      return heatRankingData.value
    default:
      return dishRankingData.value
  }
})

// 切换标签
const switchTab = (index) => {
  activeTab.value = index
  const currentKey = tabs[activeTab.value].key
  if (
    (currentKey === 'dish' && dishRankingData.value.length === 0) ||
    (currentKey === 'shop' && shopRankingData.value.length === 0) ||
    (currentKey === 'heat' && heatRankingData.value.length === 0)
  ) {
    loadRankingData()
  }
}

// 加载排行数据
const loadRankingData = async (isLoadMore = false) => {
  const currentKey = tabs[activeTab.value].key
  
  if (loading.value || (!isLoadMore && !hasMore.value[currentKey])) return
  
  loading.value = true
  const page = isLoadMore ? currentPage.value[currentKey] + 1 : 1
  
  try {
    let res
    switch (currentKey) {
      case 'dish':
        res = await getDishRankingAPI(page, 10, !isLoadMore)
        break
      case 'shop':
        res = await getMerchantRankingAPI(page, 10, !isLoadMore)
        break
      case 'heat':
        res = await getHeatRankingAPI(page, 10, !isLoadMore)
        break
    }
    
    if (res.code === 1 && res.data && res.data.records) {
      const newData = res.data.records.map((item, index) => {
        const baseData = {
          ...item,
          rank: (page - 1) * 10 + index + 1,
          image: item.image || '/static/images/default.png'
        }
        
        switch (currentKey) {
          case 'dish':
            return {
              ...baseData,
              name: item.dishName || item.name,
              score: item.dishRating !== undefined ? Number(item.dishRating) : 0,
              orderCount: item.ratingCount || item.orderCount || 0,
              price: item.price || 0,
              merchant: item.merchant || ''
            }
          case 'shop':
            return {
              ...baseData,
              name: item.merchantName || item.name,
              score: item.merchantRating !== undefined ? Number(item.merchantRating) : 0,
              orderCount: item.ratingCount || 0,
              location: item.location || '未知位置'
            }
          case 'heat':
            return {
              ...baseData,
              name: item.dishName || item.name,
              calorie: item.calorie || 0,
              price: item.price || 0,
              score: item.dishRating !== undefined ? Number(item.dishRating) : 0,
              merchant: item.merchant || ''
            }
          default:
            return baseData
        }
      })
      
      if (isLoadMore) {
        if (currentKey === 'dish') {
          dishRankingData.value = [...dishRankingData.value, ...newData]
        } else if (currentKey === 'shop') {
          shopRankingData.value = [...shopRankingData.value, ...newData]
        } else {
          heatRankingData.value = [...heatRankingData.value, ...newData]
        }
      } else {
        if (currentKey === 'dish') {
          dishRankingData.value = newData
        } else if (currentKey === 'shop') {
          shopRankingData.value = newData
        } else {
          heatRankingData.value = newData
        }
      }
      
      currentPage.value[currentKey] = page
      hasMore.value[currentKey] = res.data.records.length >= 10
    } else {
      hasMore.value[currentKey] = false
      if (!isLoadMore) {
        if (currentKey === 'dish') dishRankingData.value = []
        else if (currentKey === 'shop') shopRankingData.value = []
        else heatRankingData.value = []
      }
    }
  } catch (error) {
    console.error('加载排行数据失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 跳转详情页方法
const goToDishDetail = (dishId) => {
  uni.navigateTo({
    url: `/pages/DishDetail/index?dishId=${dishId}`
  })
}

const goToMerchantDetail = (merchantId) => {
  uni.navigateTo({
    url: `/pages/ShopDetail/index?id=${merchantId}`
  })
}

// 排名样式和图标
const getRankClass = (rank) => {
  if (rank === 1) return 'rank-first'
  if (rank === 2) return 'rank-second'
  if (rank === 3) return 'rank-third'
  return 'rank-normal'
}

const getRankIcon = (rank) => {
  if (rank === 1) return '👑'
  if (rank === 2) return '🥈'
  if (rank === 3) return '🥉'
  return rank
}

// 图片错误处理
const onImageError = (e) => {
  const imgElement = e.target
  imgElement.src = '/static/images/default-dish.png'
}

// 下拉刷新
onPullDownRefresh(async () => {
  const currentKey = tabs[activeTab.value].key
  hasMore.value[currentKey] = true
  await loadRankingData()
  uni.stopPullDownRefresh()
})

// 页面加载
onMounted(() => {
  loadRankingData()
})

// 触底加载更多
onReachBottom(() => {
  const currentKey = tabs[activeTab.value].key
  if (!loading.value && hasMore.value[currentKey] && currentRankingData.value.length > 0) {
    loadRankingData(true)
  }
})
</script>
<template>
  <view class="ranking-container">
    <!-- 页面标题 -->
    <view class="ranking-header">
      <view class="header-content">
        <view class="title-section">
          <text class="title">
            <text class="iconfont icon-paixing"></text>
            排行榜
          </text>
          <text class="subtitle">发现最受欢迎的美食与店铺</text>
        </view>
        <view class="stats-section">
          <view class="stat-item">
            <text class="stat-number">{{ currentRankingData.length }}</text>
            <text class="stat-label">上榜项目</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 切换标签 -->
    <view class="tabs-container">
      <view class="ranking-tabs">
        <view 
          v-for="(tab, index) in tabs" 
          :key="index"
          class="tab-item"
          :class="{ 'tab-active': activeTab === index }"
          @tap="switchTab(index)"
        >
          <text class="tab-label">
            <text class="iconfont" :class="`icon-${tab.icon}`"></text>
            {{ tab.name }}
          </text>
        </view>
      </view>
    </view>

    <!-- 排行榜内容 -->
    <view class="ranking-content">
      <!-- 排行榜列表 -->
      <view class="ranking-list">
        <view
          v-for="item in currentRankingData"
          :key="item.id"
          class="ranking-item"
          :class="getRankClass(item.rank)"
          @tap="tabs[activeTab].key === 'shop' ? goToMerchantDetail(item.id) : goToDishDetail(item.id)"
        >
          <!-- 排名标识 -->
          <view class="rank-badge">
            <text class="rank-number">{{ getRankIcon(item.rank) }}</text>
          </view>

          <!-- 项目图片 -->
          <view class="item-image">
            <image 
              :src="item.image" 
              mode="aspectFill"
              class="image"
              @error="onImageError"
            />
          </view>

          <!-- 项目信息 -->
          <view class="item-info">
            <text class="item-name">{{ item.name }}</text>
            <view class="item-details">
              <view class="detail-row">
                <text class="iconfont icon-weizhi"></text>
                <text class="detail-text">{{ item.location || '未知位置' }}</text>
                <view v-if="item.merchant" class="shop-tag">
                  <text>{{ item.merchant }}</text>
                </view>
              </view>
              
              <!-- 不同排行类型的详情 -->
              <view v-if="tabs[activeTab].key === 'dish'" class="detail-row">
                <text class="iconfont icon-pingfen"></text>
                <text class="detail-text">{{ item.score.toFixed(1) }}分</text>
                <text class="order-count">{{ item.orderCount }}人评价</text>
              </view>
              
              <view v-if="tabs[activeTab].key === 'shop'" class="detail-row">
                <text class="iconfont icon-pingfen"></text>
                <text class="detail-text">{{ item.score.toFixed(1) }}分</text>
                <text class="order-count">{{ item.orderCount }}人评价</text>
              </view>
              
              <view v-if="tabs[activeTab].key === 'heat'" class="detail-row">
                <text class="iconfont icon-reliang"></text>
                <text class="detail-text">{{ item.calorie }}千卡</text>
                <text class="order-count">{{ item.ratingCount }}人评价</text>
              </view>
            </view>
          </view>

          <!-- 价格/分数 -->
          <view class="item-extra">
            <view v-if="tabs[activeTab].key === 'dish' || tabs[activeTab].key === 'heat'" class="price-tag">
              <text>¥{{ item.price }}</text>
            </view>
            <view v-if="tabs[activeTab].key === 'shop'" class="score-tag">
              <text>{{ item.score.toFixed(1) }}分</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>

      <!-- 加载完成提示 - 优化样式 -->
      <view v-if="!loading && currentRankingData.length > 0 && !hasMore[tabs[activeTab].key]" class="status-message finished-message">
        <text>🎉 已经到底了~</text>
      </view>

      <!-- 下拉加载提示 - 优化样式 -->
      <view v-if="!loading && hasMore[tabs[activeTab].key] && currentRankingData.length > 0" class="status-message scroll-message">
        <text class="scroll-icon">👇</text>
        <text class="scroll-text">下拉加载更多</text>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && currentRankingData.length === 0 && hasMore[tabs[activeTab].key]" class="empty-state">
        <view class="empty-icon">
          <text class="iconfont icon-kongbai"></text>
        </view>
        <text class="empty-text">暂无排行数据</text>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.ranking-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 40rpx 32rpx calc(80rpx + env(safe-area-inset-bottom)) 32rpx;
}

// 页面标题
.ranking-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 40rpx;
  padding: 48rpx 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6rpx;
    background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
    background-size: 200% 100%;
    animation: gradientShift 3s ease-in-out infinite;
  }

  .header-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .title-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      .title {
        font-size: 44rpx;
        font-weight: 700;
        color: #333;
        margin-bottom: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        .iconfont {
          font-size: 48rpx;
          color: #667eea;
          margin-right: 20rpx;
        }
      }
      .subtitle {
        font-size: 28rpx;
        color: #666;
        opacity: 0.8;
        text-align: center;
      }
    }

    .stats-section {
      text-align: center;

      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;

        .stat-number {
          font-size: 48rpx;
          font-weight: 700;
          color: #667eea;
          line-height: 1;
        }

        .stat-label {
          font-size: 24rpx;
          color: #999;
          margin-top: 8rpx;
        }
      }
    }
  }
}

// 标签容器
.tabs-container {
  margin-bottom: 40rpx;

  .ranking-tabs {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 36rpx;
    box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.1);
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    overflow: hidden;
    display: flex;
    padding: 8rpx;

    .tab-item {
      flex: 1;
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 28rpx;
      transition: all 0.3s ease;
      position: relative;

      &.tab-active {
        background: linear-gradient(45deg, #667eea, #764ba2);
        box-shadow: 0 8rpx 16rpx rgba(102, 126, 234, 0.3);

        .tab-label {
          color: white;

          .iconfont {
            color: white;
          }
        }
      }

      .tab-label {
        display: flex;
        align-items: center;
        gap: 12rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #666;
        transition: color 0.3s ease;

        .iconfont {
          font-size: 32rpx;
          color: #999;
          transition: color 0.3s ease;
        }
      }
    }
  }
}

// 排行榜内容
.ranking-content {
  // 统一状态消息样式 - 关键优化
  .status-message {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 60rpx 40rpx;
    width: 100%;
    text-align: center;
    color: #999;
    opacity: 0.8;
    font-size: 26rpx;
  }
  
  // 下拉提示样式优化
  .scroll-message {
    gap: 12rpx;
    animation: fadeInOut 2s infinite;
    
    .scroll-icon {
      font-size: 30rpx;
    }
    
    .scroll-text {
      transition: all 0.3s ease;
    }
  }
  
  // 到底提示样式优化
  .finished-message {
    color: #b0b7cc;
    font-weight: 500;
    padding: 40rpx 0 60rpx;
  }

  .ranking-list {
    display: flex;
    flex-direction: column;
    gap: 32rpx;
    margin-bottom: 32rpx;

    .ranking-item {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(20px);
      border-radius: 32rpx;
      padding: 32rpx;
      display: flex;
      align-items: center;
      gap: 32rpx;
      box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
      border: 2rpx solid rgba(255, 255, 255, 0.2);
      transition: all 0.3s ease;
      position: relative;

      // 排名样式
      &.rank-first {
        border-left: 8rpx solid #ffd700;
        background: linear-gradient(
          135deg,
          rgba(255, 215, 0, 0.1) 0%,
          rgba(255, 255, 255, 0.95) 50%
        );
      }

      &.rank-second {
        border-left: 8rpx solid #c0c0c0;
        background: linear-gradient(
          135deg,
          rgba(192, 192, 192, 0.1) 0%,
          rgba(255, 255, 255, 0.95) 50%
        );
      }

      &.rank-third {
        border-left: 8rpx solid #cd7f32;
        background: linear-gradient(
          135deg,
          rgba(205, 127, 50, 0.1) 0%,
          rgba(255, 255, 255, 0.95) 50%
        );
      }

      .rank-badge {
        flex-shrink: 0;
        width: 80rpx;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 40rpx;
        font-weight: 700;
        border-radius: 24rpx;

        .rank-number {
          display: block;
        }
      }

      .item-image {
        flex-shrink: 0;
        width: 120rpx;
        height: 120rpx;
        border-radius: 24rpx;
        overflow: hidden;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

        .image {
          width: 100%;
          height: 100%;
        }
      }

      .item-info {
        flex: 1;
        min-width: 0;

        .item-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 16rpx;
          line-height: 1.2;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .item-details {
          display: flex;
          flex-direction: column;
          gap: 8rpx;

          .detail-row {
            display: flex;
            align-items: center;
            gap: 12rpx;
            font-size: 26rpx;
            color: #666;

            .iconfont {
              font-size: 24rpx;
              color: #999;
            }

            .detail-text {
              flex-shrink: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .shop-tag {
              background: rgba(102, 126, 234, 0.1);
              color: #667eea;
              padding: 4rpx 16rpx;
              border-radius: 16rpx;
              font-size: 22rpx;
              margin-left: auto;
              flex-shrink: 0;
            }

            .order-count {
              color: #999;
              font-size: 24rpx;
              margin-left: auto;
              flex-shrink: 0;
            }
          }
        }
      }

      .item-extra {
        flex-shrink: 0;

        .price-tag,
        .score-tag {
          background: linear-gradient(45deg, #667eea, #764ba2);
          color: white;
          padding: 12rpx 24rpx;
          border-radius: 24rpx;
          font-size: 28rpx;
          font-weight: 600;
          box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
        }
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 120rpx 40rpx;
    color: #999;

    .empty-icon {
      margin-bottom: 32rpx;

      .iconfont {
        font-size: 96rpx;
        color: #ddd;
      }
    }

    .empty-text {
      font-size: 28rpx;
    }
  }
  
  // 加载状态
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60rpx 40rpx;
    color: #999;
    opacity: 0.8;

    .loading-spinner {
      width: 48rpx;
      height: 48rpx;
      border: 4rpx solid rgba(102, 126, 234, 0.2);
      border-top: 4rpx solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 16rpx;
    }

    text {
      font-size: 26rpx;
    }
  }
}

// 新增动画效果
@keyframes fadeInOut {
  0%, 100% { opacity: 0.6; transform: translateY(0); }
  50% { opacity: 1; transform: translateY(-5rpx); }
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 响应式
@media (max-width: 480px) {
  .ranking-container {
    padding: 32rpx 24rpx calc(80rpx + env(safe-area-inset-bottom)) 24rpx;
  }

  .ranking-header {
    padding: 40rpx 32rpx;

    .header-content {
      flex-direction: column;
      gap: 32rpx;
      text-align: center;

      .title-section {
        .title {
          font-size: 40rpx;
        }
      }
    }
  }

  .ranking-content {
    .ranking-list {
      .ranking-item {
        padding: 24rpx;
        gap: 24rpx;

        .rank-badge {
          width: 64rpx;
          height: 64rpx;
          font-size: 32rpx;
        }

        .item-image {
          width: 100rpx;
          height: 100rpx;
        }

        .item-info {
          .item-name {
            font-size: 30rpx;
          }

          .item-details {
            .detail-row {
              font-size: 24rpx;
            }
          }
        }

        .item-extra {
          .price-tag, .score-tag {
            padding: 8rpx 16rpx;
            font-size: 24rpx;
          }
        }
      }
    }
  }
}
</style>